import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  // 全局共享数据
  state: {
    count: 0,
    list: [],
    key: 'unDone'
  },
  // 修改state中的数据的方法 不能直接写异步操作(无法修改state中的数据)
  mutations: {
    toggle (state, key) {
      state.key = key
    },
    setList (state, data) {
      state.list = data
    },
    add (state, v) {
      state.list.push(v)
    },
    reduce (state, id) {
      // var index = state.list.findIndex((v) => {
      //   return v.id === id
      // })
      // state.list.splice(index, 1)
      state.list.some((v) => {
        if (v.id === id) {
          state.list.splice(state.list.indexOf(v), 1)
        }
      })
    }, // 清除已完成
    clearDone (state) {
      state.list.some((v) => {
        if (v.done) {
          state.list.splice(state.list.indexOf(v), 1)
        }
      })
    }
  },
  // 这里写异步方法
  actions: {
    getList (context) {
      axios.get('/list.json').then(({ data }) => {
        context.commit('setList', data)
      })
    },

    addAsync (context, n) {
      setTimeout(() => {
        context.commit('add', n)
      }, 1000)
    },
    subAsync (context, n) {
      setTimeout(() => {
        context.commit('reduce', n)
      }, 1000)
    }
  },
  // 包装state的数据 不改变state
  getters: {
    unDone (state) {
      return state.list.filter((v) => {
        return v.done === false
      }).length
    },
    toggleList (state) {
      switch (state.key) {
        case 'all':
          return state.list
        case 'done':
          return state.list.filter((v) => {
            return v.done === true
          })
        case 'unDone':
          return state.list.filter((v) => {
            return v.done === false
          })
      }
    }
  },
  modules: {
  }
})
